package main

import (
	"fmt"
)

func main() {
	makeSlices()
	slicesChange()
	reSlices()
	sliceLenCap()
	sliceAppend()
}

func updateSlice(s []int) {
	s[0] = 100
}

// 切片的定义
func makeSlices() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	fmt.Println("切片从某位开始到结束：", arr[2:])
	fmt.Println("切片从开始到某位结束：", arr[:3])
	fmt.Println("切片左闭右开[2, 4)：", arr[2:4])
	fmt.Println("定义超过数组范围的切片：", arr[2:8])
}

// 创建切片
func slicesChange() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:]
	fmt.Println("修改之前切片的内容：", s1)
	updateSlice(s1)
	fmt.Println("修改之后切片的内容：", s1)
	fmt.Println("修改之后数组的内容：", arr)
}

// 重复切片
func reSlices() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	fmt.Println("reSlice")
	s2 := arr[:]
	fmt.Println("首次切片：", s2)
	s2 = s2[:5]
	fmt.Println("二次切片：", s2)
	s2 = s2[2:]
	fmt.Println("三次切片：", s2)
	s2 = s2[:6]
	fmt.Println("超过末尾的切片", s2)
}

// 切片的实现探究
func sliceLenCap() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5]
	fmt.Printf("s1=%v, len(s1)=%d, cap(s1)=%d\n",
		s1, len(s1), cap(s1))
	fmt.Printf("s2=%v, len(s2)=%d, cap(s2)=%d\n",
		s2, len(s2), cap(s2))
}

// append value to slice
func sliceAppend() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5]
	fmt.Printf("s1=%v, len(s1)=%d, cap(s1)=%d\n",
		s1, len(s1), cap(s1))
	fmt.Printf("s2=%v, len(s2)=%d, cap(s2)=%d\n",
		s2, len(s2), cap(s2))
	s3 := append(s2, 10)
	s4 := append(s3, 11)
	s5 := append(s4, 12)
	fmt.Println("s3, s4, s5 = ", s3, s4, s5)
	// s4 and s5 no longer view arr
	fmt.Println("arr = ", arr)
}
